//
//  HOTMenuViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-8-27.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTMenuViewController.h"
#import "HOTMainViewController.h"
#import "HOTCloseDownViewController.h"
#import "HOTStoreViewController.h"
#import "HOTOrenoCateListViewController.h"
#import "HOTDumpSearchViewController.h"
#import "HOTNewsViewController.h"
#import "NSString+extend.h"
#import "HOTMenuModel.h"
#import "HOTTolietLIstViewController.h"
#import "HOTCommBtn.h"
#import "HOTSportMainViewController.h"
#import "HOTGenbaMainViewController.h"
#import "HOTMessageBoxViewController.h"
#import "HOTNavigationViewController.h"
#import "HOTNaviBar.h"
//#import "ImobileSdkAds/ImobileSdkAds.h"
#import "GADBannerView.h"

@interface HOTMenuViewController ()

@property(nonatomic,strong)UIBarButtonItem *barBtnItem;
@end

@implementation HOTMenuViewController
{
    GADBannerView *bannerView_;
    HOTNavigationViewController *nav_;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    
    
    [super viewWillAppear:animated];
    //获取未读消息的数量
    [self requestUnreadMessages];
    
    //获取是否免费的标识
    [self requestIsFree];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = nil;
    
    [self setNaviTitle:@"MENU"];

    //[_mainScrollView setBounces:NO];
    
    [self sendRequest];

    
    self.barBtnItem = [self createBarButtomItemTarget:self action:@selector(showMessageBoxBtnClicked) image:[UIImage imageNamed:@"msg_coming_normal"] hImage:[UIImage imageNamed:@"msg_coming_normal"] edgeInsets:UIEdgeInsetsMake(0, 0, 0, -20)];
    
    //self.navigationItem.rightBarButtonItem = self.barBtnItem;
    
    // バナー広告を表示します
//    [ImobileSdkAds showBySpotID:IMOBILE_SDK_ADS_SPOT_ID ViewController:self Position:CGPointMake(0, self.view.frame.size.height - 50)];
    
    bannerView_ = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner
                                                 origin:CGPointMake(
                                                                    0,
                                                                    self.view.bounds.size.height-kGADAdSizeBanner.size.height
                                                                    )];
    bannerView_.adUnitID = ADMOB_ID;
    bannerView_.rootViewController = self;
    
    [self.view addSubview:bannerView_];
    
    [bannerView_ loadRequest:[GADRequest request]];
    
}
-(void)sendRequest {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token};
    
    __unsafe_unretained HOTMenuViewController *tempObj = self;
    [self requestWithURL:HOT_URL_MENU_LIST Parameters:parameters success:^(NSInteger result, NSArray * data) {
        
        [tempObj loadingSuccess];
        
        //将menu项信息保存到userinfo中

        tempObj.userInfo.menuList = [tempObj parseDataToMenuList:data];
        //[tempObj updateResult];
        [tempObj updateResultByFrame];

        
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)requestUnreadMessages {
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId};
    
    __unsafe_unretained HOTMenuViewController *tempObj = self;
    [self requestWithURL:HOT_URL_UNREAD_MESSAGES Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        NSLog(@"未读消息获取成功");
        
        NSString *unreadCntStr = [data objectForKey:@"unread_msg_count"];
        if ([HOTUtils isNotNullOrEmpty:unreadCntStr]) {
            
            int cnt = [unreadCntStr intValue];
            
            if (cnt > 0) {
                
                [UIApplication sharedApplication].applicationIconBadgeNumber = cnt;
                
                //有未读消息
                tempObj.navigationItem.rightBarButtonItem = tempObj.barBtnItem;
            } else {
                
                [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
                
                tempObj.navigationItem.rightBarButtonItem = nil;
            }
        }
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        NSLog(@"未读消息获取失败 %@", errMsg);
    }];
}

//请求是否免费得全局标志位
-(void)requestIsFree {
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId};
    
    __unsafe_unretained HOTMenuViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_IS_FREE Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        NSLog(@"扣费标识获取成功");
        
        if ([@"2" isEqualToString:[data objectForKey:@"is_free"]]) {
            
            //收费
            tempObj.config.isFree = NO;
        } else {
            tempObj.config.isFree = YES;
        }
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        NSLog(@"扣费标识获取失败 %@", errMsg);
    }];
}

-(NSArray *)parseDataToMenuList:(NSArray *)respData {
    
    NSMutableArray *menuList = [[NSMutableArray alloc] initWithCapacity:10];
    
    for (NSDictionary *dic in respData) {
        
        NSString *menuId = [[dic objectForKey:REQ_KEY_MENU_ID] toStr];
        NSString *priority = [[dic objectForKey:REQ_KEY_MENU_PRIORITY] toStr];
        
        HOTMenuModel *mModel = [[HOTMenuModel alloc] init];
        mModel.menu_id = menuId;
        mModel.priority = priority;
        
        [menuList addObject:mModel];
    }
    
    return menuList;
}

-(void)updateResult {
    
    NSArray *menuList = self.userInfo.menuList;
    
    //float orgY = 2;
    float padding = 30;
    NSInteger cnt = menuList.count >10 ? 10 : menuList.count;
    
    HOTCommBtn *lastBtn = nil;
    for (int i = 0; i < cnt; i ++) {
        
        HOTMenuModel *menuModel = [menuList objectAtIndex:i];
        NSString *menuId = menuModel.menu_id;
        
        HOTCommBtn *menuBtn = [HOTCommBtn buttonWithType:UIButtonTypeCustom];
        menuBtn.userInfo = @{@"menuModel":menuModel};
        
        menuBtn.translatesAutoresizingMaskIntoConstraints = NO;
        
        UIImage *menuBtnBgImage = [UIImage imageNamed:[NSString stringWithFormat:@"nav%d", [menuId intValue]-1]];
        [menuBtn setBackgroundImage:menuBtnBgImage forState:UIControlStateNormal];
        
        [_mainScrollView addSubview:menuBtn];
        
        [menuBtn addConstraint:[NSLayoutConstraint constraintWithItem:menuBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50]];
        
        [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:menuBtn attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
        
        [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:menuBtn attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
        
        if (lastBtn == nil) {
            
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:menuBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeTop multiplier:1.0 constant:padding]];
        } else {
            
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:menuBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:lastBtn attribute:NSLayoutAttributeBottom multiplier:1.0 constant:padding]];
        }
        

        
        
        //menuBtn.frame = CGRectMake(0, orgY, 320, 50);
        [menuBtn addTarget:self action:@selector(menuItemBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        
        lastBtn = menuBtn;
        
        if (i == (cnt-1)) {
            //add twitter
            HOTCommBtn *twitterBtn = [HOTCommBtn buttonWithType:UIButtonTypeCustom];
            twitterBtn.backgroundColor = [UIColor yellowColor];
            [twitterBtn setTitle:@"Twitter" forState:UIControlStateNormal];
            HOTMenuModel *twitterModel = [[HOTMenuModel alloc] init];
            twitterModel.menu_id = @"twitter";
            twitterBtn.userInfo = @{@"menuModel":twitterModel};
            
            [_mainScrollView addSubview:twitterBtn];
            
            [twitterBtn addConstraint:[NSLayoutConstraint constraintWithItem:twitterBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50]];
            
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:twitterBtn attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
            
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:twitterBtn attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
            
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:twitterBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:lastBtn attribute:NSLayoutAttributeBottom multiplier:1.0 constant:padding]];
            
            
            lastBtn = twitterBtn;
            [_mainScrollView addConstraint:[NSLayoutConstraint constraintWithItem:lastBtn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_mainScrollView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:150]];
            
        }

        //orgY = orgY + 50 + padding;
    }

//    [_mainScrollView setNeedsUpdateConstraints];
//    [_mainScrollView setNeedsLayout];
//    [_mainScrollView setNeedsDisplay];
//    [_mainScrollView layoutIfNeeded];
}

-(void)updateResultByFrame {
    
    NSArray *menuList = self.userInfo.menuList;
    
    float orgY = 2;
    float padding = 2;
    NSInteger cnt = menuList.count >10 ? 10 : menuList.count;
    for (int i = 0; i < cnt; i ++) {
        
        HOTMenuModel *menuModel = [menuList objectAtIndex:i];
        NSString *menuId = menuModel.menu_id;
        
        HOTCommBtn *menuBtn = [HOTCommBtn buttonWithType:UIButtonTypeCustom];
        menuBtn.userInfo = @{@"menuModel":menuModel};
        menuBtn.frame = CGRectMake(0, orgY, 320, 80);
        [menuBtn addTarget:self action:@selector(menuItemBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImage *menuBtnBgImage = [UIImage imageNamed:[NSString stringWithFormat:@"nav%d", [menuId intValue]-1]];
        [menuBtn setBackgroundImage:menuBtnBgImage forState:UIControlStateNormal];
        
        [_mainScrollView addSubview:menuBtn];
        
        orgY = orgY + 80 + padding;
    }
    
    //***** add twitter button *****************
    
    HOTCommBtn *twitterBtn = [HOTCommBtn buttonWithType:UIButtonTypeCustom];
    twitterBtn.backgroundColor = [UIColor yellowColor];
    twitterBtn.frame = CGRectMake(0, orgY, 320, 80);
    [twitterBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //[twitterBtn setTitle:@"Twitter" forState:UIControlStateNormal];
    [twitterBtn setBackgroundImage:[UIImage imageNamed:@"navTwitter"] forState:UIControlStateNormal];
    
    [twitterBtn addTarget:self action:@selector(twitterBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [_mainScrollView addSubview:twitterBtn];
    
    orgY = orgY + 80 + padding;
    
    //***** add twitter button *****************
    
    [_mainScrollView setContentSize:CGSizeMake(320, orgY)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)twitterBtnClicked {
    
    NSString *content = [@"   " stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *tag = [@"#現パラ" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *sharedUrl = [NSString stringWithFormat:@"http://twitter.com/intent/tweet?text=%@+%@", content, tag];
    
    //sharedUrl = @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?language=ja&location=36.572672,140.643013&radius=50000&keyword=%E3%83%88%E3%82%A4%E3%83%AC&sensor=false&key=AIzaSyCXYVinxvKf8lKl_y3BN3sgT59Q_i-zfeU";
    
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:sharedUrl]];
    
    HOTCommWebViewController *cwvc = [[HOTCommWebViewController alloc] initWithNibName:@"HOTCommWebViewController" bundle:nil url:sharedUrl];
    
    HOTNavigationViewController *hotnavc = [[HOTNavigationViewController alloc] initWithNavigationBarClass:[HOTNaviBar class] toolbarClass:nil];
    [hotnavc pushViewController:cwvc animated:NO];
    
    [self presentViewController:hotnavc animated:YES completion:nil];
}

-(void)menuItemBtnClicked:(HOTCommBtn *)sender {
    
    HOTMenuModel *menuModel = (HOTMenuModel *)[sender.userInfo objectForKey:@"menuModel"];
    if ([menuModel.menu_id isEqualToString:@"9"]) {
        //main page
        if ([self userAuthorized]) {
            HOTMainViewController *mainVC = [[HOTMainViewController alloc] initWithNibName:@"HOTMainViewController" bundle:nil];
            [self.navigationController pushViewController:mainVC animated:YES];
        }
        
    } else if ([menuModel.menu_id isEqualToString:@"2"]) {
        //倒産情報
//        if ([self userAuthorized]) {
            HOTCloseDownViewController *closeDonwVC = [[HOTCloseDownViewController alloc] initWithNibName:@"HOTCloseDownViewController" bundle:nil];
            [self.navigationController pushViewController:closeDonwVC animated:YES];
//        }
        
    } else if ([menuModel.menu_id isEqualToString:@"3"]) {
        //現場の掃き溜め
//        if ([self userAuthorized]) {
            HOTDumpSearchViewController *bbsVC = [[HOTDumpSearchViewController alloc] initWithNibName:@"HOTDumpSearchViewController" bundle:nil];
            [self.navigationController pushViewController:bbsVC animated:YES];
//        }
    } else if ([menuModel.menu_id isEqualToString:@"8"]) {
        //売店
        if ([self userAuthorized]) {
            HOTStoreViewController *storeVC = [[HOTStoreViewController alloc] initWithNibName:@"HOTStoreViewController" bundle:nil];
            [self.navigationController pushViewController:storeVC animated:YES];
        }
    } else if ([menuModel.menu_id isEqualToString:@"4"]) {
        //マイページ
        if ([self userAuthorized]) {
            HOTOrenoCateListViewController *storeVC = [[HOTOrenoCateListViewController alloc] initWithNibName:@"HOTOrenoCateListViewController" bundle:nil];
            [self.navigationController pushViewController:storeVC animated:YES];
        }
    } else if ([menuModel.menu_id isEqualToString:@"5"]) {
        //現パラニュース
        HOTCommWebViewController *newsVC = [[HOTCommWebViewController alloc] initWithNibName:@"HOTCommWebViewController" bundle:nil url:[NSString stringWithFormat:@"%@%@",HOT_URL_HOST,@"index.php/new"]];
        [newsVC setNaviTitle:@"現パラニュース"];
        [self.navigationController pushViewController:newsVC animated:YES];
    } else if ([menuModel.menu_id isEqualToString:@"10"]) {
        //便所
        HOTTolietLIstViewController *toiletVc = [[HOTTolietLIstViewController alloc] initWithNibName:@"HOTTolietLIstViewController" bundle:nil];
        [self.navigationController pushViewController:toiletVc animated:YES];
    } else if ([menuModel.menu_id isEqualToString:@"6"]) {
        //現パラスボーツ
        HOTCommWebViewController *sportsVc = [[HOTCommWebViewController alloc] initWithNibName:@"HOTCommWebViewController" bundle:nil url:[NSString stringWithFormat:@"%@%@",HOT_URL_HOST,@"index.php/new/sport"]];
        
        [sportsVc setNaviTitle:@"現パラスポーツ"];
        [self.navigationController pushViewController:sportsVc animated:YES];
        
    } else if ([menuModel.menu_id isEqualToString:@"7"]) {
        //現場の貸し借り
        if ([self userAuthorized]) {
            HOTGenbaMainViewController *genbaVc = [[HOTGenbaMainViewController alloc] initWithNibName:@"HOTGenbaMainViewController" bundle:nil];
            [self.navigationController pushViewController:genbaVc animated:YES];
        }
        
    } else if ([menuModel.menu_id isEqualToString:@"1"]) {
        //转盘
        if ([self userAuthorized]) {
            HOTCommWebViewController *dzpVc = [[HOTCommWebViewController alloc] initWithNibName:@"HOTCommWebViewController" bundle:nil url:[NSString stringWithFormat:@"%@%@?token=%@",HOT_URL_HOST,@"index.php/dzp/index",self.userInfo.token]];
            [dzpVc showToolBar:NO];
            [dzpVc setNaviTitle:@"回せ"];
            [self.navigationController pushViewController:dzpVc animated:YES];
        }
    }
    
}

-(void)showMessageBoxBtnClicked {
    
    HOTMessageBoxViewController *mbvc = [[HOTMessageBoxViewController alloc] initWithNibName:@"HOTMessageBoxViewController" bundle:nil];
    
    HOTNavigationViewController *hotnavc = [[HOTNavigationViewController alloc] initWithNavigationBarClass:[HOTNaviBar class] toolbarClass:nil];
    [hotnavc pushViewController:mbvc animated:NO];
    
    [self presentViewController:hotnavc animated:YES completion:nil];
}

- (BOOL)userAuthorized
{
    HOTUserInfo *userInfo = [HOTUserInfo defaultUser];
    
    if ([userInfo isLogined]) {
        return YES;
    } else {
        HOTEntryViewController *entryVC = [[HOTEntryViewController alloc] initWithNibName:@"HOTEntryViewController" bundle:nil];
        entryVC.delegate = self;
        [entryVC setNaviTitle:@"入場"];
        nav_ = [HOTNavigationViewController createNaviWithRootViewController:entryVC];
        [self presentViewController:nav_ animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - HOTEntryViewControllerDelegate

- (void)entrySuccessed
{
    [nav_ dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
